﻿using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using TLV.RestrictionsValidation.lexer;
using TLV.RestrictionsValidation.node;
using TLV.RestrictionsValidation.parser;

namespace TLV.RestrictionsValidation
{
    class RestrictionsValidator
    {
        private string m_Expression;
        private Start m_AST;
        public bool Result { get; private set; }

        public RestrictionsValidator(string expression)
        {
            this.m_Expression = expression;
            this.EvaluateExpression();
        }

        private void EvaluateExpression()
        {
            using (StringReader sr = new StringReader(m_Expression))
            {
                Lexer lexer = new Lexer(sr);
                Parser parser = new Parser(lexer);

                try
                {
                    //Generate AST
                    this.m_AST = parser.Parse();

                    //Calculate the result
                    ExpressionEvaluator calculator = new ExpressionEvaluator();
                    this.m_AST.Apply(calculator);
                    this.Result = calculator.CalculatedResult;
                }
                catch (Exception e)
                {
                    throw new RestrictionsValidationException(e);
                }
            }
        }

        public void PrintAST()
        {
            ASTPrinter printer = new ASTPrinter();
            this.m_AST.Apply(printer);
        }
    }
}